import React, {Component} from 'react';
import './index.less';
import {base} from 'nc-lightapp-front';
import getSubTableData from "./functions/getSubTableData";
import addLine from "./functions/addLine";
import editLine from "./functions/editLine";
import insertLine from "./functions/insertLine";
import checkDeleteLine from "./functions/checkDeleteLine";
import checkSaveLine from "./functions/checkSaveLine";
import saveLine from "./functions/saveLine";
import beforeTableEdit from "./functions/beforeTableEdit";
import afterTableEdit from "./functions/afterTableEdit";
import AlertModal from "../AlertModal";
import updateSubButtonStatus from "./functions/updateSubButtonStatus";
import {debounce} from "../../../../../../hrpub/common/utils/utils";

const {NCTabs, NCButton, NCModal} = base;
const NCTabPane = NCTabs.NCTabPane;
const {Header: NCModalHeader, Body: NCModalBody, Footer: NCModalFooter} = NCModal;

class SubTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            areaCode: props.func_type === 1 ? 'hi_psndoc_deptchg' : 'hi_psndoc_dimission',
            tableHeight: '',
            isDisablePsnVisible: false,
            isSynWorkVisible: false
        };
        this.editType = '';
        this.tabChange = this.tabChange.bind(this);
        this.onBtnOperation = this.onBtnOperation.bind(this);
        this.getSubTableData = this.getSubTableData.bind(this);
        this.saveLine = this.saveLine.bind(this);
        this.beforeEventHandle = this.beforeEventHandle.bind(this);
        this.afterEventHandle = this.afterEventHandle.bind(this);
        this.cancelEdit = this.cancelEdit.bind(this);
        this.setTableHeight = this.setTableHeight.bind(this);
    }

    componentDidMount() {
        updateSubButtonStatus.call(this, false);
        this.setTableHeight();
        window.addEventListener("resize", debounce(this.setTableHeight));
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.selectedPsn !== this.props.selectedPsn) {
            this.getSubTableData(nextProps.selectedPsn)
        }
    }

    getSubTableData(key) {
        getSubTableData.call(this, key)
    }

    tabChange(areaCode) {
        if (this.props.disabledAll) return;
        this.setState({
            areaCode
        }, () => {
            this.getSubTableData(this.props.selectedPsn)
        })
    }

    onBtnOperation(props, btncode, areacode, opt) {
        //1:新增行;2:插入行;3:修改行;4:兼职变更
        switch (btncode) {
            case 'addline':
                this.editType = 1;
                addLine.call(this);
                break;
            case 'editline':
                this.editType = 3;
                editLine.call(this);
                break;
            case 'insertline':
                this.editType = 2;
                insertLine.call(this);
                break;
            case 'deleteline':
                checkDeleteLine.call(this);
                break;
            case 'save':
                checkSaveLine.call(this);
                break;
            case 'cancel':
                this.cancelEdit();
                break;
            default:
                break;
        }
    }

    cancelEdit() {
        const {editTable, disabledAllArea} = this.props;
        editTable.cancelEdit(this.state.areaCode, () => {
            disabledAllArea(false);
            updateSubButtonStatus.call(this, false);
        })
    }

    saveLine(isSynWork, isdisablepsn) {
        const {modal, func_type} = this.props;
        if (func_type === 1) {
            this.setState({
                isSynWorkVisible: false
            });
            //modal.close('isSynWork');
            saveLine.call(this, isSynWork);
        } else {
            //modal.close('isdisablepsn');
            this.setState({
                isDisablePsnVisible: false
            });
            saveLine.call(this, undefined, isdisablepsn);
        }
    }

    beforeEventHandle(props, moduleId, item, index, value, record) {
        this.oladValue = value.value;
        return beforeTableEdit.call(this, moduleId, item.attrcode, record);
    }

    afterEventHandle(props, moduleId, key, value, changedrows, index, record) {
        afterTableEdit.call(this, moduleId, key, record, this.oladValue, index);
        /*props.handleRelationItems({
            type: 'table',               //编辑的是表单值为'form', 编辑的是表格值为'table'
            areaCode: moduleId,       //编辑区域的编码
            key: key,              //编辑字段英文名称
            value: {value: value},     //编辑字段的新值
            changedrows: [{              // 若编辑的是表格，需要传该参数(编辑字段的旧值)，表单不传
                rowid: record.rowid, // null,
                newvalue: {value: value},
                oldvalue: {value: this.oladValue}
            }],
            index: index,            //当前是第几行 ： 从 0 开始，编辑表格时，需要传该参数，表单不传
            callback: () => afterTableEdit.call(this, moduleId, key, record, this.oladValue, index),  //请求成功的回调（业务组自己的编辑后事件）,
        })*/
    }

    setTableHeight() {
        const mainTable = document.getElementsByClassName('sub-table-tabs');
        if (mainTable[0]) {
            this.setState({
                tableHeight: mainTable[0].clientHeight - 76
            })
        }
    }

    render() {
        const tabs1 = [{
            key: 'hi_psndoc_deptchg',
            text: this.props.json['hi6007-000128']/* 国际化处理： 人员任职记录*/
        }, {
            key: 'hi_psndoc_trial',
            text: this.props.json['hi6007-000130']/* 国际化处理： 人员试用情况*/
        }, {
            key: 'hi_psndoc_psnchg',
            text: this.props.json['hi6007-000129']/* 国际化处理： 人员流动情况*/
        }];

        const tabs3 = [{
            key: 'hi_psndoc_dimission',
            text: this.props.json['hi6007-000128']/* 国际化处理： 人员任职记录*/
        }, {
            key: 'hi_psndoc_psnchg',
            text: this.props.json['hi6007-000129']/* 国际化处理： 人员流动情况*/
        }, {
            key: 'hi_psndoc_retire',
            text: this.props.json['hi6007-000166']/* 国际化处理： 人员离退待遇*/
        }];
        const {areaCode, tableHeight, isDisablePsnVisible, isSynWorkVisible} = this.state;
        const {button, editTable, func_type} = this.props;
        let tabs = func_type === 1 ? tabs1 : tabs3;
        const template = this.props.meta.getMeta();
        tabs = tabs.filter(tab => template[tab.key] && template[tab.key].areaVisible);
        //如果隐藏了第一个tab页，需要重新判断设置areaCode
        if (tabs.length && tabs.findIndex(tab => tab.key === areaCode) === -1) {
            this.setState({
                areaCode: tabs[0].key
            })
        }
        return (
            <div className='sub-table-tabs'>
                <NCTabs
                    navtype="turn"
                    contenttype="moveleft"
                    tabBarPosition="top"
                    activeKey={areaCode}
                    onChange={this.tabChange}
                >
                    {
                        tabs.map(item =>
                            <NCTabPane tab={item.text} key={item.key}>
                                {
                                    editTable.createEditTable(item.key, {
                                        height: tableHeight,
                                        onBeforeEvent: this.beforeEventHandle,
                                        onAfterEvent: this.afterEventHandle
                                    })
                                }
                            </NCTabPane>)
                    }
                </NCTabs>
                <div className='sub-table-btns'>
                    {button.createButtonApp({
                        area: 'body',
                        onButtonClick: (props, btncode) => {
                            this.onBtnOperation(props, btncode, 'body', this);
                        }
                    })}
                </div>

                <AlertModal ref={node => this.alertModalNode = node} json={this.props.json}/>

                <NCModal
                    onHide={() => {
                        this.setState({
                            isSynWorkVisible: false
                        });
                    }}
                    show={isSynWorkVisible}
                    backdrop={'static'}
                >
                    <NCModalHeader
                        closeButton={true}>
                        {this.props.json['hi6007-000116']/* 国际化处理： 确认同步*/}
                    </NCModalHeader>
                    <NCModalBody>
                        <div>{this.props.json['hi6007-000115']}</div>
                        {/* 国际化处理： 是否同步履历*/}
                    </NCModalBody>
                    <NCModalFooter>
                        <NCButton colors="primary" onClick={() => this.saveLine(true)}>
                            {this.props.json['hi6007-000175']}{/* 国际化处理： 是*/}
                        </NCButton>
                        <NCButton shape="border" onClick={() => this.saveLine(false)}>
                            {this.props.json['hi6007-000176']}{/* 国际化处理： 否*/}
                        </NCButton>
                    </NCModalFooter>
                </NCModal>

                <NCModal
                    onHide={() => {
                        this.setState({
                            isDisablePsnVisible: false
                        });
                    }}
                    show={isDisablePsnVisible}
                    backdrop={'static'}
                >
                    <NCModalHeader
                        closeButton={true}>
                        {this.props.json['hi6007-000168']/* 国际化处理： 确认停用*/}
                    </NCModalHeader>
                    <NCModalBody>
                        <div>{this.props.json['hi6007-000167']}</div>
                        {/* 国际化处理： 是否同时停用当前人员*/}
                    </NCModalBody>
                    <NCModalFooter>
                        <NCButton colors="primary" onClick={() => this.saveLine(undefined, true)}>
                            {this.props.json['hi6007-000175']}{/* 国际化处理： 是*/}
                        </NCButton>
                        <NCButton shape="border" onClick={() => this.saveLine(undefined, false)}>
                            {this.props.json['hi6007-000176']}{/* 国际化处理： 否*/}
                        </NCButton>
                    </NCModalFooter>
                </NCModal>
            </div>
        );
    }
}

export default SubTable;
